<?php
declare(strict_types=1);
/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://gitee.com/xmo/MineAdmin
 */

namespace Plugin\Organization\Service;

use App\Exception\BusinessException;
use App\Http\Common\ResultCode;
use App\Service\IService;
use Common\Common;
use Plugin\Organization\Repository\RdOrganizeUserStandRepository;
use Plugin\Organization\Repository\RdOrganizeZoneRepository;

/**
 * 用户管理站点服务类
 */
final class RdOrganizeUserStandService extends IService
{
    public function __construct(
        protected readonly RdOrganizeUserStandRepository $repository,
        protected readonly RdOrganizeZoneRepository      $zoneRepository,
    )
    {
    }

    public function getAllowedUpdateData($data): array
    {
        return array_flip(['stand_id', 'role', 'status']);
    }

    public function getUserStandTree(mixed $userId): array
    {
        $userId = intval($userId);
        // 获取用户关联的所有站点ID
        $userStandIds = $this->repository->getQuery()
            ->where('user_id', $userId)
            ->get(['stand_id', 'role'])
            ->keyBy('stand_id')
            ->toArray();
        // 获取所有大区及其下级结构
        $zones = $this->zoneRepository->getQuery()->with([
            'projLines:id,name,zone_id',
            'projLines.areas:id,name,proj_line_id',
            'projLines.areas.stands:id,name,area_id'
        ])->get();

        // 构建完整的树状结构并标记用户关联的站点
        $result = [];

        foreach ($zones as $zone) {
            $zoneNode = [
                'id' => $zone->id,
                'name' => $zone->name,
                'type' => 'zone',
                'children' => []
            ];

            // 处理项目线
            foreach ($zone->projLines as $projLine) {
                $projLineNode = [
                    'id' => $projLine->id,
                    'name' => $projLine->name,
                    'type' => 'proj_line',
                    'children' => []
                ];

                // 处理工区
                foreach ($projLine->areas as $area) {
                    $areaNode = [
                        'id' => $area->id,
                        'name' => $area->name,
                        'type' => 'area',
                        'children' => []
                    ];

                    // 处理站点
                    foreach ($area->stands as $stand) {
                        $standNode = [
                            'id' => $stand->id,
                            'name' => $stand->name,
                            'type' => 'stand',
                            'checked' => isset($userStandIds[$stand->id]), // 标记是否与用户关联
                            'role' => isset($userStandIds[$stand->id]) ? $userStandIds[$stand->id]['role'] : null
                        ];
                        $areaNode['children'][] = $standNode;
                    }
                    $projLineNode['children'][] = $areaNode;
                }
                $zoneNode['children'][] = $projLineNode;
            }
            $result[] = $zoneNode;
        }

        return $result;
    }

    public function edit($data)
    {
        $userId = $data['user_id'] ?? throw new BusinessException(ResultCode::UNPROCESSABLE_ENTITY, '缺少用户ID');
        $data = $data['data'] ?? throw new BusinessException(ResultCode::UNPROCESSABLE_ENTITY, '缺少数据');
        $exists = $this->repository->getQuery()->where('user_id', $userId)->pluck('stand_id')->toArray();
        if (is_array($data)) {
            foreach ($data as $item) {
                if (!isset($item['stand_id']) || !isset($item['role']) || !isset($item['status'])) {
                    continue;
                }
                $stand_id = $item['stand_id'];
                $role = $item['role'];
                $status = $item['status'];
                
                // status为1表示添加/更新权限，2表示移除权限
                if ($status == 1) {
                    // 添加或更新权限
                    if (!in_array($stand_id, $exists)) {
                        // 添加新权限
                        $this->repository->create([
                            'user_id' => $userId,
                            'stand_id' => $stand_id,
                            'role' => $role,
                            'status' => 1
                        ]);
                    } else {
                        // 更新现有权限
                        $this->repository->getQuery()->where('user_id', $userId)->where('stand_id', $stand_id)->update([
                            'role' => $role,
                            'status' => 1
                        ]);
                    }
                } else if ($status == 2) {
                    // 移除权限
                    if (in_array($stand_id, $exists)) {
                        $this->repository->getQuery()->where('user_id', $userId)->where('stand_id', $stand_id)->delete();
                    }
                }
            }
        }
        return true;
    }

    public function setDefault(int $id, mixed $stand_id): bool
    {
        if (Common::redis()->set('user:stand:default' . $id, $stand_id)) {
            return true;
        }
        throw new BusinessException(ResultCode::UNPROCESSABLE_ENTITY, '设置默认站点失败');
    }

    public function getDefault(int $id)
    {
        return Common::redis()->get('user:stand:default' . $id);
    }

    public function getStandUser(int $stand_id)
    {
        return $this->repository->getQuery()
            ->where('stand_id', $stand_id)->where('status', 1)->where('role', '!=', 1)
            ->with('user:id,username,phone,avatar')
            ->get();
    }
}